import {Component, OnDestroy, OnInit, ViewChild, ViewEncapsulation} from '@angular/core';
import {FormGroup} from '@angular/forms';
import {ActivatedRoute, Router} from "@angular/router";
import {SignUpService} from "@sign-up/sign-up.service";

import {Subject} from "rxjs/Subject";
import {Content} from "@shared/components/toolbar/toolbar-content";
import {FormBaseComponent} from "@shared/components/form/form-base/form-base.component";
import {ImageServeService} from "@shared/service/image/image-serve.service";
import {PlatformLocation} from "@angular/common";
import {EventsService} from "@core/events/events.service";
import {ToolsService} from "@shared/service/tools/tools.service";
import {SubmitButtonComponent} from "@shared/components/submit-button/submit-button.component";
import {DynamicFormDefault, MatchSignUpData, MatchSignupFieldsResp} from "@interface/index";
// import {DynamicFormDefault, MatchSignUpData} from "@interface/shared/shared.model";
// import {MatchSignupFieldsResp} from "@interface/match/match.model";

@Component({
  selector: 'personal-match',
  templateUrl: './personal-match.component.html',
  styleUrls: ['./personal-match.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class SignUpPersonalMatchComponent implements OnInit, OnDestroy {
  @ViewChild(SubmitButtonComponent) btnWrap;
  @ViewChild('numModal') numModal; // 控制弹框的对象
  default: DynamicFormDefault = new DynamicFormDefault();
  isSgining: Boolean = false;
  loading: Boolean = true;
  signForm: FormGroup;
  hasInfo = false;  // 请求是否返回数据了
  checkSuccess = false;  // 验证成功
  checkNumData = {
    matchId: '',
    checkNum: '',
    channelsId: ''
  };
  selectArr: MatchSignupFieldsResp[];
  error = {  // 错误验证的状态
    nameIsError: false,
    phoneIsError: false,
    IDNumIsError: false,
    urgentNameIsError: false,
    urgentPhoneIsError: false,
    phoneIsRepeat: false,
  };
  params = new MatchSignUpData();
  public noInternetImg = '';  // 参赛组别
  private ngUnsubscribe: Subject<void> = new Subject<void>();
  public openCheck = false;  // 接口返回数据
  @ViewChild(Content) content;
  @ViewChild(FormBaseComponent) formBase;

  constructor(private signUpService: SignUpService,
              private route: ActivatedRoute,
              public imgSer: ImageServeService,
              private location: PlatformLocation,
              public events: EventsService,
              public toolsService: ToolsService,
              private router: Router) {
    this.noInternetImg = this.imgSer.getNoDataImg();
  }

  ngOnInit() {
    // 页面数据初始化
    this.dataInit();
    this.toolsService.setTitle('填写报名信息');
    this.location.onPopState((event) => {
      this.btnWrap.show();
    });
  }


  // 数据初始化
  dataInit() {
    // url获取渠道id
    const params = this.params;
    this.route.queryParams.subscribe((param) => {
      params.channelsId = param['channelsId'];
      params.matchId = param['matchId'];
      params.groupType = param['goodsType'];
      params.orderNumber = param['orderNumber'];
    });
    // 从获取的赛事id查询赛事详情
    this.toolsService.showLoading();
    this.signUpService.getDynamicMatchInfo(params.matchId, params.orderNumber)
      .takeUntil(this.ngUnsubscribe)
      .subscribe((res) => {
        this.toolsService.hideLoading();
        this.loading = false;
        if (res.result === '0') {
          const defaultData = new DynamicFormDefault();
          const data = res.data;
          defaultData['commingName'] = data.userName && this.checkName(data.userName) ? data.userName : '';
          defaultData['linkPhone'] = data.phone && this.checkPhone(data.phone) ? data.phone : '';
          defaultData['idNo'] = data.idNo ? data.idNo : '';
          defaultData['sex'] = data.sex ? data.sex : '';
          this.default = defaultData;
          if (data.matchSignupFields.length > 0) {
            this.selectArr = data.matchSignupFields;
          }
        } else {
          this.hasInfo = false;
          this.toolsService.showToast(res.msg);
        }
      });
  }

  checkName(str: string) {
    return !!str.match(/^[\u4e00-\u9fa5A-Za-z]*$/);
  }

  checkPhone(str: string) {
    return !!str.match(/^1[34578]\d{9}$/);
  }

  checkNumOver(success: boolean) {
    this.checkSuccess = success ?  success : false;
    // this.events.publish('modal:close');
    this.numModal.hide();
    this.numModal.goBack();
    this.openCheck = false;
  }

  // 报名
  sign() {
    if (this.isSgining) {
      return;
    }
    this.isSgining = true;
    const data = this.signUpService.getPerasonalSignData(this.params);
    if (this.params.channelsId !== 'null') {
      this.checkNumData['channelsId'] = this.params.channelsId;
    }
    const custom = {
      idNo: '',
      matchSignFieldReqs: [],
      linkPhone: '',
      sex: 0,
      commingName: '',
      birthday: ''
    };
    for (const item in this.formBase.signForm.controls) {
      if (item === 'commingName' || item === 'idNo' || item === 'linkPhone' || item === 'sex' || item === 'birthday') {
        custom[item] = this.formBase.signForm.controls[item].value;
      } else {
        // console.log(this.formBase.signForm.controls[item]);
        const temp = {
          fieldText: item,
          fieldValue: this.formBase.signForm.controls[item].value
        };
        custom['matchSignFieldReqs'].push(temp);
      }
    }

    data['matchSignDataReqList'] = [custom];
    // console.log(data);
    if ((this.default.linkPhone === custom['linkPhone'] + '')
      || (this.checkNumData.checkNum === custom['linkPhone'] + '' && this.checkSuccess)) {  // 注册手机号码跟报名号码不一致转跳到验证手机号去
      this.toolsService.showLoading();
      this.signUpService.toSign(data)
        .takeUntil(this.ngUnsubscribe)
        .subscribe((res) => {
          this.toolsService.hideLoading();
          this.isSgining = false;
          if (res.result === '0') {
            if (res.data.orderStatus === 2 || res.data.orderStatus === 1) {
              this.signUpService.goToPayOrResult(res.data.orderStatus, this.params.orderNumber);
            }  else {
              this.router.navigate(['/sign-up/personal/progress'], {queryParams: {orderNumber: this.params.orderNumber}});
            }
          } else if (res.result === '9012') {
            this.toolsService.showToast('商品已下架');
          } else if (res.result === '13002') {
            this.toolsService.showToast('提交失败，请查看订单状态是否正常');
          } else if (res.result === '9092') {
            const msgData = this.signUpService.getAgeLimitMsg(res.data);
            const temp = {
              title: `参赛人年龄不符 ${msgData.minAge} ~ ${msgData.maxAge} 岁`,
              message: `报名人: ${msgData.memberStr}`
            };
            this.toolsService.present(temp);
          } else if (res.result === '9067') {  // 用户已报名了;
            const str = this.signUpService.getHasSignMemberStr(res.data);
            const temp = {
              title: '用户已报名',
              message: str
            };
            this.toolsService.present(temp);
          } else {
            this.toolsService.showToast(res.msg);
          }
        });
    } else {
      this.isSgining = false;
      this.checkSuccess = false;
      this.checkNumData['matchId'] = this.params.matchId;
      this.checkNumData['checkNum'] = data['matchSignDataReqList'][0]['linkPhone'];
      this.events.publish('modal:show');
      // console.log(this.btnWrap);
      this.btnWrap.hide();
      // this.renderer.setElementStyle(this.btnWrap.nativeElement.querySelector('.sign-up-btn-wrap'),'display','none');
      this.openCheck = true;
      // this.content.disableScroll();
    }
  }


  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();

  }

}
